import { ref, reactive, onMounted, type Ref } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { h } from "vue";
import TaskForm from "../componentsForm/taskForm.vue";

export function useTaskTable(
  tableRef: Ref,
  lesseeId: number,
  dealerId: number,
  dealerName: string,
  tenantName: string
) {
  const form = reactive({
    SearchTerm: "",
    OrderBy: ""
  });
  const formRef = ref();
  const dataList = ref<any[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const eventOptions = ref<Array<{ value: number; label: string }>>([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 列表列定义
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "Id",
      width: 80
    },
    {
      label: "任务名称",
      prop: "Name",
      minWidth: 120
    },
    {
      label: "Cron",
      prop: "Cron",
      minWidth: 120
    },
    {
      label: "执行次数",
      prop: "ExecutionCount",
      minWidth: 120
    },
    {
      label: "状态",
      prop: "Status",
      minWidth: 100,
      slot: "status"
    },
    {
      label: "备注",
      prop: "Comment",
      minWidth: 150
    },
    {
      label: "最近执行时间",
      prop: "LastExecutionTime",
      minWidth: 150
    },
    {
      label: "下次执行时间",
      prop: "NextExecutionTime",
      minWidth: 150
    },
    {
      label: "创建时间",
      prop: "CreateTime",
      minWidth: 150
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

  // 获取、搜索任务列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm,
      tenantID: lesseeId
    };
    console.log(params);
    http
      .get(changeHttpLink("/api/Schedule"), {
        params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = (res.Data.Items || []).map(item => ({
            ...item,
            TenantName: tenantName,
            DealerName: dealerName
          }));
          pagination.total = res.Data.TotalCount || 0;
          console.log(res.Data.Items);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  // 获取事件列表用于下拉选择
  function getEventOptions() {
    http
      .get(changeHttpLink("/api/Event"), {
        params: {
          tenantId: lesseeId
        }
      })
      .then((res: any) => {
        if (res.Success) {
          // 将获取的用户列表转换为下拉列表选项
          eventOptions.value = res.Data.Items.map((item: any) => ({
            label: item.Name,
            value: item.Id
          }));
          eventOptions.value.unshift({
            label: "默认事件",
            value: 0
          });
          console.log("事件列表数据:", eventOptions.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }
  // 新增、修改任务
  function openDialog(title: string, row: any = null) {
    const id = row?.Id ?? 0;
    // 先获取事件列表
    addDialog({
      title: `${title}任务`,
      props: {
        formInline: {
          id: row?.Id ?? 0,
          dealerID: dealerId,
          tenantID: lesseeId,
          name: row?.Name ?? "",
          code: row?.Code ?? "",
          side: row?.Side ?? 0,
          cron: row?.Cron ?? "1****",
          eventId: row?.EventId ?? 0,
          params: row?.Params ?? "",
          comment: row?.Comment ?? "",
          status: row?.Status ?? 0,
          nextExecutionTime: row?.NextExecutionTime ?? "",
          lastExecutionTime: row?.LastExecutionTime ?? "",
          executionCount: row?.ExecutionCount ?? 0
        },
        title: title,
        eventOptions: eventOptions.value
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(TaskForm, {
          ref: formRef,
          formInline: null,
          title: title,
          eventOptions: eventOptions.value
        }),

      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        console.log(curData);
        function chores() {
          message(`您${title}了任务ID为【${curData.id}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              ...curData,
              tenantID: lesseeId,
              dealerID: dealerId
            };
            if (title === "创建") {
              http
                .post(changeHttpLink("/api/Schedule"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              http
                .request("put", changeHttpLink(`/api/Schedule/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  // 删除任务
  function handleDelete(row: any) {
    ElMessageBox.confirm(
      `是否确认删除任务ID为${row.Id}的这条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .request("delete", changeHttpLink(`/api/Schedule/${row.Id}`), {
            data: row.Id
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`您删除了任务ID为${row.Id}的这条数据`, {
                type: "success"
              });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Schedule/batch-delete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  // 处理当前页变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 多选框变化
  function handleSelectionChange(val: any[]) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }

  onMounted(() => {
    // 初始化加载数据
    onSearch();
    getEventOptions();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    eventOptions
  };
}
